package com.ruoyi.aitcommon.api;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.aitcommon.anotation.ApiLog;
import com.ruoyi.aitcommon.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/ait/common/hello")
public class HelloOperation {
    @Autowired
    DBOperation dbOperation;

    @ApiLog("Hello")
    @GetMapping("")
    public JSONObject getHello() {
        return JSONResult.success("hello world");
    }

    @ApiLog("Hello")
    @PostMapping("")
    public JSONObject postHello(@RequestBody String jsonstr) {
        JSONObject json=JSONObject.parseObject(jsonstr);
        return JSONResult.success(jsonstr,json);
    }

    @ApiLog("Hello header")
    @PostMapping("/header")
    public JSONObject HelloHeader(@RequestBody String jsonstr,@RequestHeader HttpHeaders headers) {
        String hello = headers.getFirst("hello");
        JSONObject json=JSONObject.parseObject(jsonstr);
        return JSONResult.success(hello,json);
    }

    @ApiLog("Hello sign")
    @PostMapping("/sign")
    public JSONObject HelloSign(@RequestBody String jsonstr,@RequestHeader HttpHeaders headers) {
        try{
            //签名验证
            if(!this.verifySign(headers)){
                throw new Exception("sign验证失败");
            }

            JSONObject json=JSONObject.parseObject(jsonstr);
            return JSONResult.success("sign",json);
        }catch (Exception ex){
            return JSONResult.error("sign",ex.getMessage());
        }
    }

    /**
     * @param headers 头部信息,含签名信息
     * @return 签名验证是否成功
     */
    private boolean verifySign(HttpHeaders headers){
        String accessKey="ruoyi";

        String sign = headers.getFirst("sign");
        String loginUser=headers.getFirst("loginUser");
        String timeStamp=headers.getFirst("timeStamp");
        final String plainText = loginUser.toString() + accessKey + timeStamp;
        final String sign1= DigestUtil.md5Hex(plainText).toUpperCase();
        if(sign.toUpperCase().equals(sign1))
            return true;
        else
            return false;
    }
}
